<?php

    require_once "weixin_info.php";

    require_once "config.php";

    $id = empty($_GET['id']) ? 0 : $_GET['id'];

    $uid=$_SESSION['Member_info'][0]['id'];

    $openid=$_SESSION['Member_info'][0]['openid'];

    $sql = $mysql->query("select * from dyspw_mem_address where  uid = {$uid} ");

    $address_list = $sql->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>

<html>



<head>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

  <title>订单确定</title>

  <script src="js/mui.min.js"></script>

  <link href="css/mui.min.css" rel="stylesheet" />

  <link href="css/goods_order.css" rel="stylesheet" />

  <script src="js/layer/layer.js" type="text/javascript"></script>
  <script src="js/dsbridge.js" type="text/javascript"></script>

  <script>

    var _hmt = _hmt || [];

    (function() {

      var hm = document.createElement("script");

      hm.src = "https://hm.baidu.com/hm.js?cb5d49b07e0a753dc8ee27ba2c73495d";

      var s = document.getElementsByTagName("script")[0];

      s.parentNode.insertBefore(hm, s);

    })();

  </script>
  <style>
      .mui-table-view:before{
        display: none;
      }
      .mui-table-view-cell:after{
        left: 0;
      }
      .mui-table-view:after{
          display: none;
      }
    #address-list-dailog{
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, .4);
        z-index: 1;
        display: none;
    }
    #address-list-log{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #fff;
        z-index: 2;
        border-radius: 7px;
        width: 80%;
        height: 336px;
        margin: auto;
        overflow:hidden;
    }
    .address-list-title1{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 2% 5%;
        box-sizing: border-box;
        border-bottom: 1px solid #c8c7cc;
    }
    .address-list-title1>p{
        margin-bottom: 0;
    }
  </style>
</head>



<body>

<div class="container takeaway" id="main-container">

    <div class="navbar waimai" id="navbar" >

        <div class="navbar-title" style="height: auto;overflow: hidden"> <div class="has-border" id="waimai">外卖</div></div>

        <div class="navbar-content-waimai">

            <div class="navbar-content-list first-content" id="address-select">

               <p class="select" id="address-name">选择地址</p>

               <input type="hidden" name="add_id" id="address-id">

               <span class="mui-icon mui-icon-arrowright"></span>

            </div>

            <p id="address-local"></p>

        </div>

    </div>



    <div class="content">

        <p class="contane-title"></p>

        <div class="goodsInfo"></div>

        <div class="detail-list is-waimai">

           <h5>包装费</h5>

            <p>￥<label class="packFree"></label></p>

        </div>

        <div class="detail-list is-waimai match_fee">

           <h5>配送费</h5>

           <p>￥<label class="deliveryFree"></label></p>

         </div>

    </div>



    <div class="remarks">

        <div id="remarks-select" class="select-detail">

            <h5>备注</h5>

            <label>

                <p id="remarks-detail">口味，偏好等要求</p>

                <span class="mui-icon mui-icon-arrowright"></span>

            </label>

        </div>

        <div id="tableware-select" class="select-detail">

            <h5>餐具数量</h5>

            <label>

                <p id="tableware-detail">未选择</p>

                <span class="mui-icon mui-icon-arrowright"></span>

            </label>

        </div>

        <div class="submit">

            <p style="color:#fff;">合计:￥<span class="totalMoney"></span></p>

            <p class="sumbit-pay" style="color:#fff;" onclick="pay()">确认支付</p>

        </div>

    </div>

    <div id="address-list-dailog">
        <div id="address-list-log">
            <div class="address-list-title1">
                <p style="color: #333; font-size: 16px">地址选择</p>

                <i class="mui-icon mui-icon-closeempty" id="close-pop"></i>
            </div>
    
            <ul class="mui-table-view mui-table-view-radio" style="overflow-y: auto;max-height: 300px">
    
                <?php foreach ($address_list as $key => $val) { ?>
    
                    <li class="mui-table-view-cell" onclick="changeaddress('<?php echo $val['add_place'] ?>', '<?php echo $val['add_brand'] ?>', '<?php echo $val['id'] ?>','<?php echo $val['add_lat'] ?>','<?php echo $val['add_lng'] ?>');" >
    
                        <a class="mui-navigate-right">
    
                            <p><?php echo $val['add_place'] ?></p>
    
                            <p><?php echo $val['add_brand'] ?></p>
    
                            <h5><?php echo $val['add_link'] ?><?php if($val['add_sex'] == 1){echo '(先生)';}else{echo '(女士)';} ?><?php echo $val['add_mobile']; ?></h5>
    
                        </a>
    
                    </li>
    
                <?php } ?>
    
                <li> <a href="address_edit.php" style="display: inline-block;width: 150px;height: 30px;background: #8D97B1;line-height: 30px;text-align: center;margin: 20px 0px;font-size: 14px;position: relative;left: 50%;transform: translateX(-50%);border-radius: 5px;color: #fff;">添加地址</a> </li>
    
            </ul>
        </div>
    </div>

    <!-- <div id="address-popover" class="mui-popover address-list">

        

    </div> -->





    <div id="remarks-popover" class="mui-popover remarks-pop address-list">

        <div class="address-list-title">

            <i class="mui-icon mui-icon-closeempty" id="close-remarks"></i>

            <p>备注</p>

        </div>

        <textarea name="txtarea" onblur="changeReamrk(this)" id="txtarea" rows="5" cols="10" placeholder="备注信息"></textarea>

        <p id="closeButton" style="text-align: center">确定</p>

    </div>



    <div id="tableware-popover" class="mui-popover address-list">

        <div class="address-list-title"><p>餐具选择</p></div>

        <div class="tableware-list">

            <p onclick="changetableware('tableware-one', '无需餐具')" id="tableware-one">无需餐具<br/>

                <span>(筷子，刀，勺，吸管）</span>

            </p>

            <p onclick="changetableware('tableware-two', '1份')" id="tableware-two">1份</p>

            <p onclick="changetableware('tableware-three', '2份')" id="tableware-three">2份</p>

            <p onclick="changetableware('tableware-four', '3份')" id="tableware-four">3份</p>

            <p onclick="changetableware('tableware-five', '4份')" id="tableware-five">4份</p>

            <p onclick="changetableware('tableware-six', '5份')" id="tableware-six">5份</p>

        </div>

    </div>

</div>



  <script src="./js/jquery-2.2.4.min.js"></script>

  <script type="text/javascript" src="//webapi.amap.com/maps?v=1.4.1&key=fedad41056b27c3e8cc5eaca216434e9"></script>

  <script>

      $(function () {

          mui.init();

          // 地址选择

          $("#address-select").click(function() {
                $('#address-list-dailog').css('display','block')
            //   mui('#address-popover').popover('toggle', document.getElementById("openPopover"));

          });

          // 关闭选择地址
          
          $("#address-list-dailog").click(function(event) {

            $('#address-list-dailog').css('display','none')

        });

          $("#close-pop").click(function() {

            $('#address-list-dailog').css('display','none')

          });



          // 餐具选择

          $("#tableware-select").click(function() {

              mui('#tableware-popover').popover('toggle', document.getElementById("openPopover"));

          });



          $("#close-tableware").click(function() {

              mui('#tableware-popover').popover('toggle', document.getElementById("openPopover"));

          });



          // 备注

          $("#remarks-select").click(function() {

              mui('#remarks-popover').popover('toggle', document.getElementById("openPopover"));

          });



          $("#close-remarks").click(function() {

              mui('#remarks-popover').popover('toggle', document.getElementById("openPopover"));

          });



          $("#closeButton").click(function() {

              mui('#remarks-popover').popover('toggle', document.getElementById("openPopover"));

          });

      });



      var shopId=<?php echo $id?>;

      var sswId=0;

      var money=0;

      var shopCar=localStorage.getItem('shopCar') ? JSON.parse(localStorage.getItem('shopCar')) : {};



      // 重新选择地址

      function changeaddress(name, address,id,lat,lng) {

          $("#address-name")[0].innerText = name;

          $("#address-local")[0].innerText = address;

          $("#address-id").val(id);

          $('#address-list-dailog').css('display','none')

          var url = '/order/price/';

          var param = {'dispatch_mode':1,'shop_id':15,'receiver_longitude':lng,'receiver_latitude':lat,

              'receiver_address':address};

          $.ajax({

              url: "shipping.php",

              type: "post",

              data: {'url':url, 'param':param},

              dataType: 'JSON',

              success: function(res) {

                  res = JSON.parse(res);

                  if(res.code == 1){

                      $(".deliveryFree").html(res.data.min_price);

                      $(".totalMoney").html(Number(money)+Number(res.data.min_price));

                  }else{

                      layer.open({

                          content: res.message,

                          skin: 'msg',

                          time: 3

                      });

                      $("#address-id").attr('value','');

                  }

              }

          })

      }





      // 餐具选择

      function changetableware(id, text) {

          $("#tableware-one")[0].className = "";

          $("#tableware-two")[0].className = "";

          $("#tableware-three")[0].className = "";

          $("#tableware-four")[0].className = "";

          $("#tableware-five")[0].className = "";

          $("#tableware-six")[0].className = "";

          $("#" + id)[0].className = "tableware-active";

          $("#tableware-detail")[0].innerText = text;

          mui('#tableware-popover').popover('toggle', document.getElementById("openPopover"));

      }



      function changeReamrk(e) {

          if (e.value) {

              $("#remarks-detail")[0].innerText = e.value;

          } else {

              $("#remarks-detail")[0].innerText = '口味，偏好等要求';

          }

      }





      if(shopCar[shopId]){

          $.ajax({

              url:'api/order.php?action=goodList',

              type:'POST',

              async:false,

              data:{'shop_id':shopId,'goods':JSON.stringify(shopCar[shopId])},

              dataType:'json',

              success:function(res){

                 if(!res.code){

                    $(".contane-title").html(res.data.shopname);

                    var html='';

                    $.each(res.data.goods,function (index,val) {

                        html +=' <div class="detail"><div class="detail-flex"><img src="'+val.img+'"><div><h4>'+val

                            .title+'</h4><p id="ajax-number">X '+val.num+'</p></div></div><div><h5>￥'+val.money+'</h5></div></div>'

                    });

                    $(".goodsInfo").html(html);

                    $(".packFree").html(res.data.pack_fee);

                    $(".deliveryFree").html(res.data.delivery_fee);

                    $(".totalMoney").html(res.data.total_money);

                    money=res.data.money;

                    sswId = res.data.ssw_id

                 }else{

                     alert(res.message);

                     window.location.href='delivery_center.php?id='+shopId;

                 }

              }

          })

      }else {

          window.location.href='delivery_center.php?id='+shopId;

      }





      //支付

      function pay(){

          var add_id = $("#address-id").val();
          var remarks = $("#remarks-detail")[0].innerText === '口味，偏好等要求' ? '' : $("#remarks-detail")[0].innerText;// 备注
          var meal_num = parseInt($("#tableware-detail")[0].innerText.slice(0,1));
          var deliveryFree =$(".deliveryFree").html();  //配送费
          if (!add_id) {
              layer.open({
                  content: '请选择配送地址',
                  skin: 'msg',
                  time: 2
              });
              return false;
          }
          if(window.navigator.userAgent == 'AndroidNative'){
			$.ajax({
				url : "./api/appPay.php?action=takeFood",
				type: "post",
				data:{
					'shop_id':shopId,
                    'goods':JSON.stringify(shopCar[shopId]),
                    'remarks': remarks,
                    'add_id': add_id,
                    'deliveryFree': deliveryFree,
                    'uid':<?php echo $uid?>,
                    'meal_num': typeof meal_num === 'number' && !isNaN(meal_num) ? meal_num : 0,             //餐具数量
                    "payMethod": "aliPay"
				},
				dataType:'JSON',
				success:function(ret){
					if(!ret.code){
						dsBridge.call("aliPay", {
							data: ret.data
						});
					}else{
						alert(ret.message)
					}
				}
			})
		}else if(window.navigator.userAgent == 'IosNative'){
			$.ajax({
				url : "./api/appPay.php?action=takeFood",
				type: "post",
				data:{
					'shop_id':shopId,
                    'goods':JSON.stringify(shopCar[shopId]),
                    'remarks': remarks,
                    'add_id': add_id,
                    'deliveryFree': deliveryFree,
                    'uid':<?php echo $uid?>,
                    'meal_num': typeof meal_num === 'number' && !isNaN(meal_num) ? meal_num : 0,             //餐具数量
                    "payMethod": "aliPay"
				},
				dataType:'JSON',
				success:function(ret){
					if(!ret.code){
						dsBridge.call("aliPay", {
							data: ret.data
						});
					}else{
						alert(ret.message)
					}
				}
			})
		}else{
            $.ajax({
              url:'api/order.php?action=goodList&payStatus=true',
              type:'POST',
              async:false,
              data:{
                  'shop_id':shopId,
                  'goods':JSON.stringify(shopCar[shopId]),
                  'remarks': remarks,
                  'add_id': add_id,
                  'deliveryFree': deliveryFree,
                  'openid':'<?php echo $openid?>',
                  'uid':<?php echo $uid?>,
                  'meal_num': typeof meal_num === 'number' && !isNaN(meal_num) ? meal_num : 0,             //餐具数量
              },
              dataType:'json',
              success:function(res){
                  if(res.code){
                      layer.open({
                          content: res.message,
                          skin: 'msg',
                          time: 2
                      });
                      return false;
                  }
                  WeixinJSBridge.invoke(
                      'getBrandWCPayRequest', {
                          "appId": res.data.appId,
                          "timeStamp": res.data.timeStamp,
                          "nonceStr": res.data.nonceStr,
                          "package": res.data.package,
                          "signType": res.data.signType,
                          "paySign": res.data.paySign,

                      },

                      function(result){

                          if(result.err_msg == "get_brand_wcpay_request:ok" ){

                              layer.open({ content: "支付成功", skin: 'msg', time: 2 });

                              //清空本地购物车

                              shopCar[shopId]=[];

                              localStorage.setItem('shopCar',JSON.stringify(shopCar));

                              setTimeout(function(){window.location.href="order_list.php";}, 1000);

                          }else if(result.err_msg == "get_brand_wcpay_request:cancel"){

                              layer.open({ content: "您已取消支付", skin: 'msg', time: 2 });

                          }else{

                              layer.open({ content: "支付异常", skin: 'msg', time: 2 });

                          }

                      }

                  );



              }

          })
		}

      }

  </script>

</body>

</html>

